<template>
  <div style="width: 100%">
    <el-select
      v-model="orgName"
      filterable
      placeholder="请选择机构"
      style="margin: 10px;width: 40%"
      @change="changeOrg"
    >
      <el-option
        v-for="lo in orgNameList"
        :key="lo.orgId"
        :label="lo.orgName"
        :value="lo.orgId"
      />
    </el-select>
    <el-date-picker
      v-model="createDateRange"
      type="daterange"
      align="right"
      unlink-panels
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      :picker-options="pickerOptions"
      value-format="yyyy-MM-dd"
      style="width: 50%"
      @change="resetData"
    />
    <el-menu default-active="1" class="el-menu-demo" mode="horizontal" @select="changeData">
      <el-menu-item index="1">销售额  {{ allSaleAmt }}</el-menu-item>
      <el-menu-item index="2">来客数  {{ guestNum }}</el-menu-item>
      <el-menu-item index="3">客单价  {{ guestCost }}</el-menu-item>
      <el-menu-item index="4">毛利额  {{ profit }}</el-menu-item>
      <el-menu-item index="5">毛利率  {{ profitRate }} </el-menu-item>
    </el-menu>
    <div>
      <div id="chart_example" />
    </div>
    <div style="margin-top: 20px;border: 0px;width: 100%">
      <el-table
        :data="saleDetils"
        :header-cell-style="{fontWeight:'normal',color:'#52b0d8'}"
        :row-style="{height: '20px'}"
        :cell-style="{padding : '5px 0',border:'0px',marginLeft:'20px'}"
        class="my-el-table"
      >
        <template slot="empty">
          <span style="font-size: 20px" />
        </template>
        <el-table-column
          prop="goodsInfo"
          label="销售额top10商品（编码/名称）"
          :width="(screenWidth*0.30)"
          :render-header="labelHead"
          show-overflow-tooltip
        />
        <el-table-column
          prop="saleAmt"
          label="销售额"
          :width="(screenWidth*0.11)"
          :render-header="labelHead"
          show-overflow-tooltip
        />
        <el-table-column
          prop="saleNum"
          label="销售量"
          :width="(screenWidth*0.12)"
          :render-header="labelHead"
          show-overflow-tooltip
        />
        <el-table-column
          prop="saleBillNum"
          label="销售单数"
          :width="(screenWidth*0.11)"
          :render-header="labelHead"
          show-overflow-tooltip
        />
        <el-table-column
          prop="profitRate"
          label="毛利率"
          :width="(screenWidth*0.11)"
          :render-header="labelHead"
          show-overflow-tooltip
        />
        <el-table-column
          prop="storNum"
          label="库存"
          :width="(screenWidth*0.1)"
          :render-header="labelHead"
          show-overflow-tooltip
        />
        <el-table-column
          prop="turnoverDay"
          label="周转天数"
          :width="(screenWidth*0.11)"
          :render-header="labelHead"
          show-overflow-tooltip
        />
      </el-table>
    </div>
  </div>
</template>

<script>
import { getOrgDoc, getSaleOverview, getSaleReporting } from '@/api/erpHome'
import echarts from 'echarts'
export default {
  name: 'SaleDetail',
  data() {
    return {
      screenWidth: document.body.clientWidth,
      pickerOptions: {
        disabledDate(date) {
          // disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
          if (date.getTime() < Date.now()) {
            return false
          } else {
            return true
          }
        },
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      saleDetils: [],
      saleData: {},
      orgNameList: [],
      orgName: '',
      orgId: '',
      orgNames: [],
      startDate: '',
      entDate: '',
      createDateRange: '',
      allSaleAmt: '',
      guestCost: '',
      guestNum: '',
      memSaleAmt: '',
      profit: '',
      profitRate: '',
      showXData: [],
      showYData: [],
      reportField: 'SALEAMT',
      timesType: '',
      showName: ''
    }
  },
  watch: {
    createDateRange(time) {
      if (time) {
        this.startDate = time[0]
        this.entDate = time[1]
      } else {
        this.startDate = ''
        this.entDate = ''
      }
    },
    screenWidth(val) {
      // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
      if (!this.timer) {
        // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
        this.screenWidth = val
        this.timer = true
        const that = this
        setTimeout(function() {
          // 打印screenWidth变化的值
          console.log(this.screenWidth)
          that.timer = false
        }, 400)
      }
    }
  },
  mounted() {
    const that = this
    window.onresize = () => {
      return (() => {
        window.screenWidth = document.body.clientWidth
        that.screenWidth = window.screenWidth
      })()
    }
    this.drawLine()
  },
  created() {
    this.defaultDate()
    this.getOrgDoc()
  },
  methods: {
    resetData() {
      if (this.orgId === '') {
        this.orgId = this.orgNameList[0].orgId
        this.orgName = this.orgNameList[0].orgName
      }
      if (this.startDate === '' || this.entDate === '') {
        this.$message({
          message: '请选择时间',
          type: 'warning'
        })
        return
      }
      if (new Date(this.startDate).getTime() < new Date(this.entDate).getTime() - 1000 * 3600 * 24 * 90) {
        this.$message({
          message: '时间跨度不能超过90天',
          type: 'warning'
        })
        return
      }
      this.getSaleReporting()
      this.getSaleOverview()
    },
    // 默认时间
    defaultDate() {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      end.setTime(end.getTime() - 3600 * 1000 * 24 * 1)
      this.createDateRange = [start, end]
      this.startDate = this.timestampToTime(end)
      this.entDate = this.timestampToTime(start)
      console.log(this.startDate)
    },
    getOrgDoc() {
      const params = {
      }
      getOrgDoc({ ...params }).then(res => {
        this.orgNameList = res.data
        this.orgId = res.data[0].orgId
        this.orgName = res.data[0].orgName
        this.resetData()
      })
        .finally(_ => {
          this.loading = false
        })
    },
    changeData(index) {
      switch (index) {
        case '1': this.reportField = 'SALEAMT'; break
        case '2': this.reportField = 'CUSTNUM'; break
        case '3': this.reportField = 'CUSTBILLPRICE'; break
        case '4': this.reportField = 'PROFIT'; break
        case '5': this.reportField = 'PROFITRATE'; break
        default : this.reportField = 'SALEAMT'; break
      }
      this.$store.state.adminleftnavnum = index
      if (this.orgId === '') {
        this.orgId = this.orgNameList[0].orgId
        this.orgName = this.orgNameList[0].orgName
      }
      if (this.startDate === '' || this.entDate === '') {
        this.$message({
          message: '请选择时间',
          type: 'warning'
        })
        return
      }
      if (new Date(this.startDate).getTime() < new Date(this.entDate).getTime() - 1000 * 3600 * 24 * 90) {
        this.$message({
          message: '时间跨度不能超过90天',
          type: 'warning'
        })
        return
      }
      this.getSaleReporting()
      this.drawLine()
    },
    changeOrg(val) {
      this.orgId = ''
      this.orgName = ''
      let obj = {}
      obj = this.orgNameList.find((item) => {
        return item.orgId === val
      })

      if (obj != null) {
        this.orgName = obj.orgName
        this.orgId = obj.orgId
        this.resetData()
      } else {
        this.orgName = ''
        this.orgId = ''
      }
    },
    getSaleOverview(payload) {
      const params = {
        selectOrgId: this.orgId,
        startDate: this.timestampToTime(this.startDate),
        entDate: this.timestampToTime(this.entDate)
      }
      getSaleOverview({
        ...params
      })
        .then(res => {
          this.saleData = res.data
          this.saleDetils = this.saleData.saleDetils
        })
        .finally(_ => {
          this.loading = false
        })
    },
    // 重画图表
    drawLine() {
      const myChart = echarts.init(document.getElementById('chart_example'))
      const option = {
        color: ['#52b0d8'],
        tooltip: {
          trigger: 'axis'
        },
        xAxis:
                        [
                          {
                            type: 'category',
                            data: this.showXData,
                            axisTick: {
                              alignWithLabel: true
                            }
                          }
                        ],
        // x轴拖动
        // dataZoom: [
        //   {
        //     type: 'slider',
        //     realtime: true, // 拖动滚动条时是否动态的更新图表数据
        //     height: 25, // 滚动条高度
        //     start: 0, // 滚动条开始位置（共100等份）
        //     end: 100 // 结束位置（共100等份）
        //   }
        // ],
        yAxis:
                        [
                          {
                            type: 'value'
                          }
                        ],
        series:
                        [
                          {
                            smooth: true,
                            name: this.showName,
                            type: 'line',
                            data: this.showYData
                          }
                        ]
      }
      myChart.setOption(option) // 建议加上以下这一行代码，不加的效果图如下（当浏览器窗口缩小的时候）。超过了div的界限（红色边框）
      window.addEventListener('resize', function() { myChart.resize() })
    },
    labelHead(h, { column }) {
      const l = column.label.length
      const f = 14
      column.minWidth = f * l
      return h('div', { class: 'table-head', style: { width: '150%', height: '28px', marginLeft: '-10px' }}, [column.label])
    },
    getSaleReporting(payload) {
      this.timesType = 'DAY'
      if (this.timestampToTime(this.startDate) === this.timestampToTime(this.entDate)) {
        this.timesType = 'HOUR'
      }
      const params = {
        reportField: this.reportField,
        reportOrgId: this.orgId,
        startTime: this.timestampToTime(this.startDate),
        endTime: this.timestampToTime(this.entDate),
        timesType: this.timesType
      }
      Object.assign(params, payload)
      getSaleReporting({
        ...params
      })
        .then(res => {
          const index = this.reportField
          switch (index) {
            case 'SALEAMT': this.showYData = res.data.saleAmts; this.showName = '销售额'; break
            case 'CUSTNUM': this.showYData = res.data.countNums; this.showName = '来客数'; break
            case 'CUSTBILLPRICE': this.showYData = res.data.costBillPrices; this.showName = '客单价'; break
            case 'PROFIT': this.showYData = res.data.profits; this.showName = '毛利额'; break
            case 'PROFITRATE': this.showYData = res.data.profitRates; this.showName = '毛利率'; break
            default : this.showYData = res.data.saleAmts; break
          }
          const xindex = this.timesType
          switch (xindex) {
            case 'DAY': this.showXData = res.data.dates; break
            case 'HOUR': this.showXData = res.data.times; break
            default : this.showXData = res.data.dates; break
          }
          if (JSON.stringify(res.data.head) !== '{}' && res.data.head !== null) {
            this.allSaleAmt = res.data.head.saleAmt + '元'
            this.guestCost = res.data.head.custBillPrice + '元'
            this.guestNum = res.data.head.custNum + '人'
            this.profit = res.data.head.profit + '元'
            this.profitRate = res.data.head.profitRate + '%'
          } else {
            this.allSaleAmt = ''
            this.guestCost = ''
            this.guestNum = ''
            this.profit = ''
            this.profitRate = ''
          }
          this.drawLine()
        })
        .finally(_ => {
          this.loading = false
        })
    },
    timestampToTime(row) {
      const date = new Date(row)
      const Y = date.getFullYear() + '-'
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      const D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' '
      return Y + M + D
    }
  }
}
</script>

<style scoped>
  .my-el-table{
    position:static;
  }
  .el-menu-demo{
    border-bottom: solid 0px;
  }
  .el-menu-item{
    font-weight: bold;
    color: #2d3a4b;
  }
  .el-menu-item.is-active{
    color: #52b0d8 !important;
    border-bottom: 2px solid #52b0d8 ;
  }
  #chart_example{
    width: 106%;
    height: 320px;
    border: 0px;
    margin: -20px 0px -40px -30px;
  }
</style>
